
package com.borqs.music.tasks;

import static com.borqs.music.http.RequestMethod.GET;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.http.HttpRequest;
import com.borqs.music.http.HttpResponse;
import com.borqs.music.model.SingerInfo;
import com.borqs.music.util.MusicConf;
import com.borqs.music.util.MusicConf.ReqType;

public class GetSingerAreaTask extends Task {

    private String mTicket;

    public GetSingerAreaTask(TaskListener singerAreaListener, String ticket) {
        super(singerAreaListener);
        this.mTicket = ticket;
    }

    @Override
    public HttpRequest prepareRequest() {
        String url = MusicConf.getUrl(ReqType.MUSIC_SINGER_AREA);
        HttpRequest req = new HttpRequest(GET, url, mTicket, null);
        return req;
    }

    @Override
    public Object handleResponse(HttpResponse resp) throws Exception {
        checkResponse(resp);
        JSONArray jArr = resp.asJSONArray();
        List<SingerInfo> singers = decodeSingerAreaJSONArray(jArr);
        return singers;
    }

    private List<SingerInfo> decodeSingerAreaJSONArray(JSONArray jArr) throws JSONException {
        List<SingerInfo> singers = new ArrayList<SingerInfo>(10);
        for (int i = 0, len = jArr.length(); i < len; i++) {
            JSONObject jObj;
            jObj = jArr.getJSONObject(i);
            SingerInfo singer = new SingerInfo();
            singer.id = jObj.getInt("area_id");
            singer.name = jObj.getString("area_name");
            singer.imgUrl = jObj.getString("area_img_url");
            singers.add(singer);
        }
        return singers;
    }
}
